package pers.cl.dubbo.gateway.channel.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.cl.dubbo.mvc.DispatchServlet;

import java.lang.reflect.InvocationTargetException;

/**
 * @author chenlei
 * @date 2020-01-07
 * @see DispatchServlet
 **/
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private DispatchServlet dispatchServlet;

    public HttpRequestHandler(DispatchServlet dispatchServlet) {
        this.dispatchServlet = dispatchServlet;
    }

    /*
     * @author chenlei
     * @date 2020-01-07
     * @description
     * @see io.netty.channel.SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, java.lang.Object)
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        // TODO
        String result = null;
        FullHttpResponse response = null;
        try{
            result = dispatchServlet.doDispatch(req, null);
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1
                    , HttpResponseStatus.OK,
                    Unpooled.copiedBuffer(result, CharsetUtil.UTF_8));
        }catch (Exception e){
            if (e instanceof InvocationTargetException) {
                result = ((InvocationTargetException) e).getTargetException().getMessage();
            }else{
                result = e.getMessage();
            }
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1
                    , HttpResponseStatus.BAD_REQUEST,
                    Unpooled.copiedBuffer(result, CharsetUtil.UTF_8));
        }
        response.headers().set("Content-Type", "text/plain;charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

}
